package com.wlyuan.open.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlyuan.mybatis.utils.RepositoryUtils;
import com.wlyuan.open.dao.entity.OpenApiInfoLogDO;
import com.wlyuan.open.dao.mapper.OpenApiInfoLogMapper;
import com.wlyuan.open.domain.api.OpenApiInfoLog;
import com.wlyuan.open.domain.api.OpenApiInfoLogId;
import com.wlyuan.open.domain.api.respository.OpenApiInfoLogRepository;
import com.wlyuan.open.infrastructure.converter.OpenApiInfoLogConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lijing
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OpenApiInfoLogRepositoryImpl implements OpenApiInfoLogRepository {
    private final OpenApiInfoLogMapper mapper;

    @Override
    public OpenApiInfoLog ofId(@NotNull OpenApiInfoLogId id) {
        return OpenApiInfoLogConverter.convert(mapper.selectById(id.getId()));
    }

    @Override
    public OpenApiInfoLogId save(OpenApiInfoLog data) {
        if (CollectionUtils.isEmpty(data.getApis())) {
            return null;
        }
        var save = RepositoryUtils.save(mapper,
                OpenApiInfoLogConverter::convert,
                data, data.getId());

        data.setId(new OpenApiInfoLogId(save.getId()));
        return data.getId();
    }

    @Override
    public void remove(OpenApiInfoLogId id) {
        mapper.deleteById(id.getId());
    }

    @Override
    public List<OpenApiInfoLog> list(Collection<OpenApiInfoLogId> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<Long> idList = ids.stream().map(OpenApiInfoLogId::getId).collect(Collectors.toList());
        LambdaQueryWrapper<OpenApiInfoLogDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OpenApiInfoLogDO::getId, idList).orderByDesc(OpenApiInfoLogDO::getId);
        return OpenApiInfoLogConverter.convert(mapper.selectList(queryWrapper));
    }

}
